/**
 * 影院模块的路由
 */
const Router = require('koa-router');
const router = new Router(); 
const getDb = require('../db');
const ObjectId  = require('mongodb').ObjectId;


router.all('/cinema/add', async (ctx) => {
try {
    let data = {
        ...ctx.params,
        cTime:Date.now(),
        uTime:Date.now()
    }
    let dbo = await getDb();
    await dbo.collection('cinema').insertOne(data);
    ctx.body={
        code:1,
        meg:'成功了',
        data
    };
} catch (error) {
    ctx.body={
        code:0,
        meg:error.message
    }
}
});

router.all('/cinema/list', async ctx => { 
try {
    let dbo = await getDb();
 let res = await dbo.collection('cinema').find({}).toArray();
    ctx.body = {
       code:1,
       meg:'影院列表',
       res
    }
} catch (error) {
    ctx.body={
        code:0,
        meg:error.message
    }
}
});

router.all('/cinema/del', async ctx => {
    if(!ctx.params.id){
        ctx.body = {
            code:0,
            msg:'请提供id参数'
        };
        return false;
    }
try {
    let id = ctx.params.id
    let dbo = await getDb();
  let res = await dbo.collection('cinema').deleteOne({
        _id:ObjectId(id)
    });
    if(res.deleteCount > 0){
        ctx.body={
            code:1,
            mge:'删除成功',
        }
    }else{
        ctx.body={
            code:0,
            meg:'删除失败'
        }
    }
   
} catch (error) {
    ctx.body={
        code:0,
        meg:error.message
    }
}
});

router.all('/cinema/edit', async ctx => {
try {
    let dbo = await getDb();
    let res = await dbo.collection('cinema').updateOne({ _id: ObjectId(id)}, {
        $set: data
    })
    ctx.body = {
        code: 1,
        msg: `成功更新${res.modifiedCount}条数据`,
        data: res
    }
} catch (error) {
    ctx.body={
        code:0,
        meg:error.message
    }
}
});


// 把router导出
module.exports = router;